package com.mohe.shanpao.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class EchoServer {
	public static void main(String[] args) throws InterruptedException
	{
		EventLoopGroup boss = new NioEventLoopGroup(1);
		EventLoopGroup work = new NioEventLoopGroup();
		
		try
		{
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(boss, work).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP));
					pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
//					pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
//					pipeline.addLast("decoder", new StringDecoder());
//				    pipeline.addLast("encoder", new StringEncoder());
				    
					pipeline.addLast("decoder",new MessageDecoder());
					pipeline.addLast("encoder", new MessageEncoder());
					
					pipeline.addLast(new EchoServerHandler());
					
//					pipeline.addLast(new EchoServerOuboundHandler());
				}
			}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
			
			ChannelFuture future = bootstrap.bind(9009).sync();
			future.channel().closeFuture().sync();
			
		} finally {
			work.shutdownGracefully();
			boss.shutdownGracefully();
		}
	}
}
